package com.smartlink.app.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.smartlink.app.R;
import com.smartlink.app.activity.BluetoothActivity;
import com.smartlink.app.adapter.GridItemAdapter;
import com.smartlink.app.common.Constant;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


public class InDoorFragment extends Fragment {

    private static final String TAG = "InDoorFragment:";
    private SharedPreferences sharedPreferences;

    private GridView gv_in_door_grid;
    private TextView tv_in_door_address, tv_in_door_date, tv_in_door_temperature, tv_in_door_kong_tiao;

    private Switch switch_in_door_light, switch_in_door_curtain;
    private SeekBar sb_in_door_fan;


    private String[] titles = {"室内湿度", "一氧化碳含量", "光照强度", "土壤湿度"};
    private String[] values = {"0", "0", "0", "0"};
    private int[] images = {R.drawable.shi_du, R.drawable.pm25, R.drawable.sun_black, R.drawable.shi_du};

    private boolean havaClassRoomId = false;
    private String classRoomId;

    private SensorManager sensorManager;
    private Sensor lightSensor;
    private float lightValue;

    private boolean lightState = false;
    private boolean curtainState = false;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x1:
                    //更新数据
                    Map<String, String> map = (Map<String, String>) msg.obj;
                    values[0] = map.get("roomRh");
                    values[1] = "0.96";
                    values[2] = lightValue + "";
                    values[3] = map.get("soilRh");
                    tv_in_door_temperature.setText(map.get("roomTemperature") + " ℃");
                    Toast.makeText(getContext(), "数据更新完成", Toast.LENGTH_SHORT).show();
                    break;
                case 0x3:
                    //发生错误
                    Toast.makeText(getContext(), "数据获取失败，请稍后再试", Toast.LENGTH_SHORT).show();
                    break;
                case 0x4:
                    Toast.makeText(getContext(), "网络错误", Toast.LENGTH_SHORT).show();
                    break;

            }

        }
    };

    private SensorEventListener lightListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            lightValue = event.values[0];
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    public InDoorFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_in_door, container, false);
        sharedPreferences = getContext().getSharedPreferences("main", Context.MODE_PRIVATE);
        //检查教室id
        checkClassRoomId();
        //绑定数据
        bindView(rootView);
        //注册光照传感器
        sensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
        lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        sensorManager.registerListener(lightListener, lightSensor, SensorManager.SENSOR_DELAY_UI);
        return rootView;

    }

    private void bindView(View rootView) {
        tv_in_door_address = (TextView) rootView.findViewById(R.id.tv_in_door_address);
        tv_in_door_date = (TextView) rootView.findViewById(R.id.tv_in_door_date);
        tv_in_door_temperature = (TextView) rootView.findViewById(R.id.tv_in_door_temperature);
        tv_in_door_kong_tiao = (TextView) rootView.findViewById(R.id.tv_in_door_kong_tiao);
        switch_in_door_light = (Switch) rootView.findViewById(R.id.switch_in_door_light);
        switch_in_door_curtain = (Switch) rootView.findViewById(R.id.switch_in_door_curtain);
        sb_in_door_fan = (SeekBar) rootView.findViewById(R.id.sb_in_door_fan);
        gv_in_door_grid = (GridView) rootView.findViewById(R.id.gv_in_door_grid);
        GridItemAdapter gridItemAdapter = new GridItemAdapter(getContext(), titles, values, images);
        gv_in_door_grid.setAdapter(gridItemAdapter);

        //设置控制按钮监听事件
        switch_in_door_light.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switch_in_door_light.setEnabled(false);
                light();
            }
        });

        switch_in_door_curtain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switch_in_door_curtain.setEnabled(false);
                curtain();
            }
        });

        sb_in_door_fan.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                fan(seekBar.getProgress());
            }
        });
    }

    @Override
    public void onResume() {
        setDate();
        if (havaClassRoomId) {
            isTeacher();
            updateData();
        } else {
            viewDisEnable();
        }

        super.onResume();
    }

    @Override
    public void onDestroy() {
        sensorManager.unregisterListener(lightListener, lightSensor);
        super.onDestroy();
    }

    /**
     * 更新显示时间
     */
    private void setDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String date = sdf.format(new Date());
        tv_in_door_date.setText(date);
    }

    public void updateData() {
        String classRoomName = sharedPreferences.getString("classRoomName", "");
        tv_in_door_address.setText(classRoomName);
        //刷新数据
        getEnvicloud();

    }

    public void viewDisEnable() {
        switch_in_door_curtain.setEnabled(false);
        switch_in_door_light.setEnabled(false);
        sb_in_door_fan.setEnabled(false);

    }

    public void isTeacher() {
        int userType = sharedPreferences.getInt("userType", 0);
        if (userType == 999) {
            switch_in_door_curtain.setVisibility(View.VISIBLE);
            switch_in_door_light.setVisibility(View.VISIBLE);
            sb_in_door_fan.setVisibility(View.VISIBLE);

            switch_in_door_curtain.setEnabled(true);
            switch_in_door_light.setEnabled(true);
            sb_in_door_fan.setEnabled(true);
        } else {
            switch_in_door_curtain.setVisibility(View.INVISIBLE);
            switch_in_door_light.setVisibility(View.INVISIBLE);
            sb_in_door_fan.setVisibility(View.INVISIBLE);
            tv_in_door_kong_tiao.setVisibility(View.INVISIBLE);
        }

    }

    /**
     * 判断是否存在教室Id
     */
    private void checkClassRoomId() {
        //判断是否有教室ID

        classRoomId = sharedPreferences.getString("classRoomId", "");
        Log.i(TAG, "checkClassRoomId: " + classRoomId);
        if (classRoomId.equals("")) {
            Intent intent = new Intent(getContext(), BluetoothActivity.class);
            startActivityForResult(intent, 0x111);
        } else {
            havaClassRoomId = true;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x111) {
            if (resultCode == BluetoothActivity.RESULT_SUCCESS) {
                havaClassRoomId = true;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 获取室内环境状况
     *
     * @return
     */
    public void getEnvicloud() {
        //获取教室环境
        String ip = sharedPreferences.getString("ip", Constant.HTTP.HTTP_PORT);
        String pathRoomEnv = "http://" + ip + ":8080/smartlink/getEnvData?clsroomId=" + classRoomId;
        System.out.println(pathRoomEnv);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.get(pathRoomEnv, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String body = new String(responseBody);
                try {
                    Map<String, String> map = new HashMap<String, String>();
                    JSONObject jsonObject = new JSONObject(body);
                    JSONObject jsonObjectData = (JSONObject) jsonObject.get("data");
                    JSONArray datastreams = (JSONArray) jsonObjectData.get("datastreams");
                    for (int i = 0; i < 4; i++) {
                        JSONObject jsonObject1 = (JSONObject) datastreams.get(i);
                        String key = (String) jsonObject1.get("id");
                        JSONArray datapoints = (JSONArray) jsonObject1.get("datapoints");
                        String value = (String) ((JSONObject) datapoints.get(0)).get("value");
                        map.put(key, value);
                    }

                    Message message = handler.obtainMessage();
                    message.what = 0x1;
                    message.obj = map;
                    handler.sendMessage(message);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                handler.obtainMessage(0x3);
            }
        });

    }


    /**
     * 控制灯光
     */
    public void light() {
        String ip = sharedPreferences.getString("ip", Constant.HTTP.HTTP_PORT);
        String lightPath = "http://" + ip + ":8080/smartlink/controlLight?clsroomId=" + classRoomId + "&cmdValue=";
        String path;
        if (lightState) {
            path = lightPath + 0;
        } else {
            path = lightPath + 1;
        }
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.get(path, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                switch_in_door_light.setEnabled(true);
                lightState = !lightState;

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                switch_in_door_light.setEnabled(true);
                handler.obtainMessage(0x4);
            }
        });
    }

    /**
     * 风扇开关
     *
     * @param progress
     */
    public void fan(int progress) {
        String ip = sharedPreferences.getString("ip", Constant.HTTP.HTTP_PORT);
        String fanPath = "http://" + ip + ":8080/smartlink/controlFan?clsroomId=" + classRoomId + "&cmdValue=";
        String path;
        if (progress >= 50) {
            path = fanPath + 1;
        } else {
            path = fanPath + 0;
        }
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.get(path, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                handler.obtainMessage(0x4);
            }
        });
    }


    /**
     * 控制窗帘
     */
    public void curtain() {
        String ip = sharedPreferences.getString("ip", Constant.HTTP.HTTP_PORT);
        String curtainPath = "http://" + ip + ":8080/smartlink/controlCurtain?clsroomId=" + classRoomId + "&cmdValue=";
        String path;
        if (curtainState) {
            path = curtainPath + 1;

        } else {
            path = curtainPath + 0;
        }
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.get(path, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                switch_in_door_curtain.setEnabled(true);
                curtainState = !curtainState;
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                switch_in_door_curtain.setEnabled(true);
                handler.obtainMessage(0x4);
            }
        });
    }


}
